package com.example.greenshuttle;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMapLoadedListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.example.greenshuttle.data.MarkerMsg;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 接受2个位置名称，在地图上显示路线
 */
public class MapDiscriptionActivity extends Activity implements
		OnMarkerClickListener, OnInfoWindowClickListener, OnMapLoadedListener,
		InfoWindowAdapter {
	// implement , OnGeocodeSearchListener

	private String TIME;
	private String NUM;
	private String START_PLACE;
	private String END_PLACE;

	// startplace 经纬度
	private Double SLAT;
	private Double SLNG;
	// endplace 经纬度
	private Double ELAT;
	private Double ELNG;

	// amap绘图
	private AMap aMap;
	private MapView mapView;
	private Marker marker2;// 有跳动效果的marker对象
	private static final LatLng defaultPlace = new LatLng(34.341568, 108.940174);

	// private MarkerMsg StartPlace_MMsg = new MarkerMsg(30.679879, 104.064855,
	// "成都市", "成都市:30.679879, 104.064855");
	// private MarkerMsg EndPlace_MMsg = new MarkerMsg(34.341568, 108.940174,
	// "西安市", "西安市:34.341568, 108.940174");
	private MarkerMsg StartPlace_MMsg = null;
	private MarkerMsg EndPlace_MMsg = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map_discription);
		getBundleMsg();

		// 初始化进度条
		ProgressDialog_init();

		StartPlace_MMsg = new MarkerMsg(SLAT, SLNG, START_PLACE, START_PLACE
				+ "经纬度：" + String.valueOf(SLAT) + ";" + String.valueOf(SLNG));
		EndPlace_MMsg = new MarkerMsg(ELAT, ELNG, END_PLACE, END_PLACE + "经纬度："
				+ String.valueOf(ELAT) + ";" + String.valueOf(ELNG));

		// //地址转换为坐标
		// GeocodeSearch_init();
		// placeToLatlng();

		// map init
		mapView = (MapView) findViewById(R.id.activity_map_amap2d);
		mapView.onCreate(savedInstanceState); // 此方法必须重写
		init();

	}

	/**
	 * 获取从上一个activity传递下来的信息
	 */
	private void getBundleMsg() {
		Bundle bundle = this.getIntent().getExtras();

		TIME = bundle.getString("time");
		NUM = bundle.getString("num");
		START_PLACE = bundle.getString("startplace");
		END_PLACE = bundle.getString("endplace");

		// show msg
		String s = "TIME:" + TIME + ",NUM:" + NUM + ",START_PLACE:"
				+ START_PLACE + ",END_PLACE:" + END_PLACE;
		Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();

		SLAT = bundle.getDouble("slat");
		SLNG = bundle.getDouble("slng");
		ELAT = bundle.getDouble("elat");
		ELNG = bundle.getDouble("elng");
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
	}

	private void setUpMap() {
		aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
		aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
		addMarkersToMap();// 往地图上添加marker
		addPolylineToMap();// 往地图上添加polyline
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	private void addMarkersToMap() {
		// 1。添加起点,anchor(0.5f, 0.5f)代表以，长和宽的中线交点为中心//anchor(0.5f,
		// 1f)表示图片的底部中间位于点position上
		MarkerOptions mo_start = new MarkerOptions().anchor(0.5f, 1f)
				.position(this.StartPlace_MMsg.getPosition())
				.title(this.StartPlace_MMsg.getTitle())
				.snippet(this.StartPlace_MMsg.getSnippet()).draggable(true)
				.icon(BitmapDescriptorFactory.fromResource(R.drawable.start));
		aMap.addMarker(mo_start);
		// 2.添加终点
		MarkerOptions mo_end = new MarkerOptions().anchor(0.5f, 1f)
				.position(this.EndPlace_MMsg.getPosition())
				.title(this.EndPlace_MMsg.getTitle())
				.snippet(this.EndPlace_MMsg.getSnippet()).draggable(true)
				.icon(BitmapDescriptorFactory.fromResource(R.drawable.end));
		aMap.addMarker(mo_end);
	}

	private void addPolylineToMap() {
		// 绘制一个起点到终点的线
		aMap.addPolyline((new PolylineOptions()).add(
				this.StartPlace_MMsg.getPosition(),
				this.EndPlace_MMsg.getPosition()).color(Color.RED));
	}

	/**
	 * 对marker标注点点击响应事件
	 */
	@Override
	public boolean onMarkerClick(final Marker marker) {
		if (marker.equals(marker2)) {
			if (aMap != null) {
				jumpPoint(marker);
			}
		}
		Toast.makeText(getApplicationContext(), "你点击的是" + marker.getTitle(),
				Toast.LENGTH_SHORT).show();
		return false;
	}

	/**
	 * marker点击时跳动一下
	 */
	public void jumpPoint(final Marker marker) {
		final Handler handler = new Handler();
		final long start = SystemClock.uptimeMillis();
		Projection proj = aMap.getProjection();
		Point startPoint = proj.toScreenLocation(defaultPlace);
		startPoint.offset(0, -100);
		final LatLng startLatLng = proj.fromScreenLocation(startPoint);
		final long duration = 1500;

		final Interpolator interpolator = new BounceInterpolator();
		handler.post(new Runnable() {
			@Override
			public void run() {
				long elapsed = SystemClock.uptimeMillis() - start;
				float t = interpolator.getInterpolation((float) elapsed
						/ duration);
				double lng = t * defaultPlace.longitude + (1 - t)
						* startLatLng.longitude;
				double lat = t * defaultPlace.latitude + (1 - t)
						* startLatLng.latitude;
				marker.setPosition(new LatLng(lat, lng));
				aMap.invalidate();// 刷新地图
				if (t < 1.0) {
					handler.postDelayed(this, 16);
				}
			}
		});

	}

	/**
	 * 监听点击infowindow窗口事件回调
	 */
	@Override
	public void onInfoWindowClick(Marker marker) {
		Toast.makeText(getApplicationContext(),
				"你点击了infoWindow窗口" + marker.getTitle(), Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * 监听amap地图加载成功事件回调
	 */
	@Override
	public void onMapLoaded() {
		LatLngBounds bounds = new LatLngBounds.Builder()
				.include(StartPlace_MMsg.getPosition())
				.include(EndPlace_MMsg.getPosition()).build();
		aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

	}

	@Override
	public View getInfoContents(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	// ////////////////////////////////////////////////////////////////
	// 进度条部分
	private ProgressDialog progDialog = null;

	private void ProgressDialog_init() {
		progDialog = new ProgressDialog(this);
	}

	/**
	 * 显示进度条对话框
	 */
	public void showDialog() {
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在获取地址");
		progDialog.show();
	}

	/**
	 * 隐藏进度条对话框
	 */
	public void dismissDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}

	// /////////////////////////////////////////////////////////////////
	// //文字地址转换为坐标
	// // getLatlon("方恒国际中心");
	// private GeocodeAddress GeoAddressTem = null;
	//
	// /**
	// * Geo搜索
	// */
	// private GeocodeSearch geocoderSearch;
	//
	// private void GeocodeSearch_init() {
	// geocoderSearch = new GeocodeSearch(this);
	// geocoderSearch.setOnGeocodeSearchListener(this);
	// }
	//
	// private void placeToLatlng() {
	// //显示进度条
	// showDialog();
	//
	// getLatlon(this.START_PLACE);
	// if(GeoAddressTem.getLatLonPoint() != null) {
	// this.StartPlace_MMsg = new MarkerMsg(GeoAddressTem.getLatLonPoint(),
	// this.START_PLACE, GeoAddressTem.getFormatAddress());
	// }
	// GeoAddressTem = null;
	// try {
	// Thread.sleep(500);
	// } catch (InterruptedException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// getLatlon(this.END_PLACE);
	// if(GeoAddressTem.getLatLonPoint() != null) {
	// this.EndPlace_MMsg = new MarkerMsg(GeoAddressTem.getLatLonPoint(),
	// this.END_PLACE, GeoAddressTem.getFormatAddress());
	// }
	// GeoAddressTem = null;
	//
	// //隐藏进度条
	// dismissDialog();
	// }
	//
	// /**
	// * 响应地理编码
	// */
	// public void getLatlon(final String name) {
	// GeocodeQuery query = new GeocodeQuery(name, "021");//
	// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
	// geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
	// }
	//
	// /**
	// * 地理编码查询回调
	// */
	// @Override
	// public void onGeocodeSearched(GeocodeResult result, int rCode) {
	// if (rCode == 0) {
	// if (result != null && result.getGeocodeAddressList() != null
	// && result.getGeocodeAddressList().size() > 0) {
	// GeocodeAddress address = result.getGeocodeAddressList().get(0);
	//
	// //包含经度和维度：address.getLatLonPoint()
	// String addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
	// + address.getFormatAddress();
	//
	// this.GeoAddressTem = address;
	//
	// Toast.makeText(getApplicationContext(), addressName,
	// Toast.LENGTH_SHORT).show();
	// } else {
	// Toast.makeText(getApplicationContext(), "no_result",
	// Toast.LENGTH_SHORT).show();
	// }
	//
	// } else if (rCode == 27) {
	// Toast.makeText(getApplicationContext(), "error_network",
	// Toast.LENGTH_SHORT).show();
	// } else if (rCode == 32) {
	// Toast.makeText(getApplicationContext(), "error_key",
	// Toast.LENGTH_SHORT).show();
	// } else {
	// Toast.makeText(getApplicationContext(), "error_other",
	// Toast.LENGTH_SHORT).show();
	// }
	// }
	//
	// @Override
	// public void onRegeocodeSearched(RegeocodeResult arg0, int arg1) {
	// // TODO Auto-generated method stub
	//
	// }
	//

}
